﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ZhouYu.NewWorld.BLL.IService;
using ZhouYu.NewWorld.Model;
using ZhouYu.NewWorld.ViewModel;
using ZhouYu.NewWorld.Web.Models;

namespace ZhouYu.NewWorld.Web.Controllers
{
    public class LoginController : Controller
    {
        //注入
        private ILoginService _loginService;
        public LoginController(ILoginService loginService)
        {
            _loginService = loginService;
        }



        public JsonResult Logins(Admin admin,bool check)
        {
            //创建返回结果对象
            ResponseResult responseResult = new ResponseResult();
            Admin admins = new Admin();
            Expression<Func<Admin, bool>> lambdaExpression = a => a.AdminName == admin.AdminName && a.AdminPwd == admin.AdminPwd;
            admins = _loginService.Query(lambdaExpression);
            responseResult.Success = admins != null;
            if (admins != null)
            {
                responseResult.Success = true;
                //判断是否点击记住密码
                if (check)
                {
                    //存储session值
                    AdminUserContext.adminContext.Admin = admins;
                    //如果选中保存密码则存储cookie

                    //存储cookie
                    //创建一个Cookie对象
                    HttpCookie httpCookie = new HttpCookie("CookieName");
                    //设置Cookie的值
                    httpCookie.Values.Add("AdminName", admins.AdminName);
                    httpCookie.Values.Add("AdminPwd", admins.AdminPwd);
                    httpCookie.Values.Add("DateTime", DateTime.Now.AddDays(7).ToString("yyyy-MM-dd HH:mm:ss"));
                    //设置Cookie的过期时间
                    httpCookie.Expires = DateTime.Now.AddDays(7);
                    System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie);
                }//不记住密码
                else
                {
                    //存储session值
                    AdminUserContext.adminContext.Admin = admins;
                    //如果选中保存密码则存储cookie

                    //存储cookie
                    //创建一个Cookie对象
                    HttpCookie httpCookie = new HttpCookie("CookieName");
                    //设置Cookie的值
                    httpCookie.Values.Add("AdminName", admins.AdminName);
                    System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie);
                }
                }
            return Json(responseResult);
        }
        //退出登录
        public ActionResult LoginOut()
        {

              //清除Session
            AdminUserContext.adminContext.Admin = null;
            //退出
            FormsAuthentication.SignOut();
            return Redirect("/Home/Login");
        }
    }
}